@layout BlogLayout
@page "/admin/blog/import/"
@inject HttpClient _http
@inject IStringLocalizer<Resource> _localizer
@inject IToaster _toaster
@inject IJSRuntime JSRuntime

<PageTitle Title="@_localizer["import"]" />

@if (Posts == null)
{
    <h1 class="section-title">@_localizer["import"]</h1>
    <div class="section-content -half">
        <EditForm Model="@ImportModel" OnValidSubmit="GetEntries">
            <DataAnnotationsValidator />
            <div class="form-item">
                <label class="form-label">@_localizer["website-URL"]</label>
                <input class="form-control" type="text" @bind="ImportModel.BaseUrl" placeholder="https://example.com" />
                <ValidationMessage For="@(() => ImportModel.BaseUrl)"></ValidationMessage>
            </div>
            <div class="form-item">
                <label class="form-label">@_localizer["feed-URL"]</label>
                <input class="form-control" type="text" @bind="ImportModel.FeedUrl" placeholder="https://example.com/feed.xml" />
                <ValidationMessage For="@(() => ImportModel.FeedUrl)"></ValidationMessage>
            </div>
            <div class="form-item">
                <button class="btn btn-blogifier px-5" type="submit">@_localizer["load"]</button>
            </div>
        </EditForm>
    </div>
}
else {
    <div class="section-content">
        <div class="section-title">@Posts.Count @_localizer["import-message-found"].</div>
        <div class="list-toolbar">
            <label class="list-check form-check" data-bs-toggle="tooltip" title="@_localizer["select-all"]">
                <input type="checkbox" class="list-check-input form-check-input" @onchange="EventArgs => { CheckAll(EventArgs.Value); }">
                <span>@_localizer["import-all"]</span>
            </label>
        </div>
        <ul id="import-list" class="list mb-4">
            @foreach (var post in Posts)
            {
                <li class="list-item">
                    <label class="list-check form-check" id="@post.Slug" data-bs-toggle="tooltip" title="@_localizer["select"]">
                        <input type="checkbox" class="list-check-input form-check-input" style="display: block" @bind="post.Selected">
                    </label>
                    <span class="list-icon ps-0 pe-3" id="s-@post.Slug" style="display:none;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-check text-success" viewBox="0 0 16 16" data-bs-toggle="tooltip" title="@_localizer["published"]">
                            <path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z"/>
                        </svg>
                    </span>
                    <span class="list-icon ps-0 pe-3" id="f-@post.Slug" style="display:none;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" class="bi bi-exclamation-triangle-fill text-danger" viewBox="0 0 16 16">
                            <path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
                        </svg>
                    </span>
                    <div class="list-title">@post.Title</div>
                    <div class="list-text ms-auto">@post.Published.ToFriendlyShortDateString()</div>
                </li>
            }
        </ul>
        <div class="alert @StatusMsgCss mb-4">@StatusMsg</div>
        <div class="form-item">
            <button class="btn btn-blogifier px-5 me-3" type="button" @onclick="Import">@_localizer["import"]</button>
            <button class="btn btn-default" type="button" @onclick="Load">@_localizer["cancel"]</button>
        </div>
    </div>
}

@code {
    protected ImportModel ImportModel { get; set; }
    protected List<Post> Posts { get; set; }
    protected string StatusMsg { get; set; }
    protected string StatusMsgCss { get; set; }

    protected override void OnInitialized()
    {
        Load();
    }

    protected void Load()
    {
        ImportModel = new ImportModel { FeedUrl = "" };
        Posts = null;
        StatusMsg = "";
        StatusMsgCss = "d-none";
    }

    protected async Task GetEntries()
    {
        Posts = await _http.GetFromJsonAsync<List<Post>>($"api/syndication/getitems?feedUrl={ImportModel.FeedUrl}&baseUrl={ImportModel.BaseUrl}");
    }

    protected async Task Import()
    {
        int successCnt = 0;
        int failedCnt = 0;

        foreach (var post in Posts)
        {
            if (!post.Selected)
                continue;

            var result = await _http.PostAsJsonAsync<Post>("api/syndication/import", post);
            if (result.IsSuccessStatusCode)
            {
                await JSRuntime.InvokeAsync<string>("commonJsFunctions.replaceElement", post.Slug, true);
                successCnt++;
            }
            else
            {
                await JSRuntime.InvokeAsync<string>("commonJsFunctions.replaceElement", post.Slug, false);
                failedCnt++;
            }
        }

        if (failedCnt == 0 && successCnt > 0) {
            StatusMsg = $"Imported {successCnt} posts.";
            StatusMsgCss = $"alert-success";
        }
        else {
            StatusMsg = $"Imported {successCnt} posts out of {successCnt + failedCnt}. Please check logs for errors.";
            StatusMsgCss = $"alert-warning";
        }
    }

    public void CheckAll(object checkValue)
    {
        bool isChecked = (bool)checkValue;
        Posts.ForEach(p => p.Selected = isChecked);
        StateHasChanged();
    }
}
